package org.lilystudio.veryftp.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

/**
 * ��ȡ��������Ŀ������� <b>����ʹ�ò���·������Ĺ��췽��</b>
 * 
 * @author Goodtiger
 * @version 1.0.0
 */
public class PropertiesUtil {

	private FileInputStream fis;

	private FileOutputStream fos;

	private String path;

	private Properties prop = new Properties();

	private File file;

	/**
	 * �Զ�Ѱ��Properties.properties�ļ����ڵ�λ�ã�����ļ������ڣ����½����ļ�
	 * 
	 */
	public PropertiesUtil() {
		path = System.getProperty("catalina.home")
				+ System.getProperty("file.separator") + "webapps"
				+ System.getProperty("file.separator") + "VeryFTP"
				+ System.getProperty("file.separator") + "WEB-INF"
				+ System.getProperty("file.separator") + "classes"
				+ System.getProperty("file.separator")
				+ "Properties.properties";
		this.createFile(path);
		System.out.println(path);
	}

	/**
	 * ����ָ����·��4��b Properties.properties�ļ�
	 * 
	 * @param path
	 *            Properties.properties�ļ���·��
	 */
	public PropertiesUtil(String path) {
		this.path = path;
		this.createFile(this.path);
		System.out.println(path);
	}

	/**
	 * ��bProperties.properties�ļ�
	 * 
	 * @param path
	 *            Properties.properties�ļ���·��
	 */
	private void createFile(String path) {
		file = new File(path);
		if (!file.exists()) {
			try {
				fos = new FileOutputStream(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * �õ�key���Ӧ��ֵ,���û�ж�Ӧ��Key����IOException������""
	 * 
	 * @param key
	 * @return key���Ӧ��ֵ
	 */

	public String getProperty(String key) {
		String value = "";
		try {
			fis = new FileInputStream(path);
			prop.load(fis);
			value = prop.getProperty(key);
			return value;
		} catch (IOException e) {
			e.printStackTrace();
			return value;
		} finally {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * �� Properties.properties�ļ���д������ֵ
	 * 
	 * @param key
	 * @param value
	 */
	public void setProperty(String key, String value) {
		try {
			if (fis == null) {
				fis = new FileInputStream(path);
			}
			prop.load(fis);
			prop.setProperty(key, value);
			fis.close();
			if (fos == null) {
				fos = new FileOutputStream(path);
				prop.store(fos, "=========Update " + new Date().toString()
						+ "================");
			}

		} catch (IOException e) {
			e.printStackTrace();

		} finally {

			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

}
